package pers.xiaoliang.concurrency.example.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @version v1.0
 * @description: 使用ForkJoin框架
 * @author: xiaoliang.liu
 * @date: 2018/7/29 9:29
 */
@Slf4j
public class ForkJoinTaskExample1 extends RecursiveTask<Integer> {

    public static final int threshold = 2;
    private int start;
    private int end;


    public ForkJoinTaskExample1(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;

        // 如果任务足够小就计算任务(小于等于2不能二分了)
        boolean canCompute = (end - start) <= threshold;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 如果任务大于阈值，就分裂成两个子任务计算
            int middle = (start + end) / 2;
            ForkJoinTaskExample1 leftTask = new ForkJoinTaskExample1(start, middle);
            ForkJoinTaskExample1 rightTask = new ForkJoinTaskExample1(middle + 1, end);

            // 执行子任务
            leftTask.fork();
            rightTask.fork();

            // 等待任务执行结束合并它们执行后返回的结果
            Integer leftResult = leftTask.join();
            Integer rightResult = rightTask.join();
            sum = leftResult + rightResult;
        }

        return sum;
    }


    public static void main(String[] args) {
        // 创建一个ForkJoin池
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        // 生成一个计算任务(计算1+2+3...100)
        ForkJoinTaskExample1 task = new ForkJoinTaskExample1(2, 5);

        // 执行一个任务
        ForkJoinTask<Integer> result = forkJoinPool.submit(task);

        try {
            log.info("result: {}", result.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }
}
